package com.leiqichao.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leiqichao.backend.entity.Media;
import com.leiqichao.backend.mapper.MediaMapper;
import com.leiqichao.backend.service.MediaService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.UUID;

@Service
public class MediaServiceImpl extends ServiceImpl<MediaMapper, Media> implements MediaService {
    @Value("${file.upload-dir:uploads}") 
    private String uploadDir;

    private final MediaMapper mediaMapper;

    public MediaServiceImpl(MediaMapper mediaMapper) {
        this.mediaMapper = mediaMapper;
    }

    @Transactional
    @Override
    public Media uploadFile(MultipartFile file, String uploaderName) throws IOException {
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileExt = originalFilename.substring(originalFilename.lastIndexOf("."));
        String storedFilename = UUID.randomUUID() + fileExt;
        
        // 创建存储目录
        Path uploadPath = Paths.get(uploadDir);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }
        
        // 存储文件
        Path filePath = uploadPath.resolve(storedFilename);
        Files.copy(file.getInputStream(), filePath);

        // 保存记录
        Media media = new Media();
        media.setName(originalFilename);
        media.setPath(storedFilename);
        media.setMimeType(file.getContentType());
        media.setSize(file.getSize());
        media.setUploaderName(uploaderName);
        save(media);
        
        return media;
    }

    @Transactional
    @Override
    public boolean safeDelete(Long id) {
        Media media = getById(id);
        if (media == null || media.getIsDeleted()) {
            return false;
        }

        // 物理删除文件
        try {
            Path filePath = Paths.get(uploadDir, media.getPath());
            Files.deleteIfExists(filePath);
        } catch (IOException e) {
            throw new RuntimeException("文件删除失败", e);
        }

        // 逻辑删除记录
        return removeById(id);
    }
}